package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IStrategyService;
import cn.wolfcode.trip.base.service.IRegionService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 地区资源控制器
 */


@RestController
@RequestMapping("regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext servletContext;

    /**
     * 查询所有地区
     * @return
     */
    @GetMapping
    public List<Region> lsitAll(Integer state){

        return regionService.listAll(state);
    }

    /**
     * 查询某地区的攻略,返回(html)
     * @param qo
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void getstrategyByRegionId(StrategyQueryObject qo, HttpServletResponse response)
            throws Exception {
        //查询某个地区的推荐攻略时 不分页
        qo.setState(Strategy.STATE_HOT);
        qo.setPageSize(0);
        PageInfo<Strategy> hot = strategyService.query(qo);
        //查询某个地区的所有攻略时 分页
        qo.setState(null);
        qo.setPageSize(4);
        PageInfo<Strategy> all = strategyService.query(qo);
        //创建freemarker配置对象
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        //配置模板目录
        configuration.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("template")));
        //去找某个模板
        configuration.setDefaultEncoding("utf-8");
        Template template = configuration.getTemplate("strategyTemplate.ftl");
        //合成数据
        HashMap<Object, Object> map = new HashMap<>();
        map.put("hot",hot);
        map.put("all",all);
        //设置响应编码
        response.setContentType("text/html;charset=utf-8");
        template.process(map,response.getWriter());
    }


    /**
     * 查询某地区的攻略,返回(json)
     * @param qo
     * @return
     */
    @GetMapping(value = "{regionId}/strategies",produces = "application/json;charset=utf-8")
    public PageInfo getstrategyByRegionId(StrategyQueryObject qo){
        qo.setPageSize(4);
        return strategyService.query(qo);

    }

}
